package com.ruoyi.flowable.listener.asset;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.equ.domain.EquStockin;
import com.ruoyi.equ.service.IEquStockinService;
import com.ruoyi.flowable.service.IWorkOrderAssetRelService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;

/**
 * 验收-驳回 验收最终状态、验收完成时间
 */
@Slf4j
@Component("assetRejectListener")
public class AssetRejectListener implements ExecutionListener {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    private static final IWorkOrderAssetRelService workOrderAssetRelService = SpringUtils.getBean(IWorkOrderAssetRelService.class);

    @Override
    public void notify(DelegateExecution execution) {
        try {
            IEquStockinService stockinService = SpringUtils.getBean(IEquStockinService.class);
            SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            EquStockin equStockin = execution.getVariable("equStockin", EquStockin.class);

            //验收最终状态
            String acceptanceStatus = "未通过";

            //验收完成时间
            Date finishTime = sdfTime.parse(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            //审批信息
            String approvalInfo = equStockin.getApprovalInfo();
            Map<String, Object> approvalInfoMap = objectMapper.readValue(
                    approvalInfo,
                    new TypeReference<Map<String, Object>>() {});
            approvalInfoMap.put("验收最终状态", acceptanceStatus);
            approvalInfoMap.put("验收完成时间", finishTime);
            approvalInfo = objectMapper.writeValueAsString(approvalInfoMap);

            //赋值
            equStockin.setAcceptanceStatus(acceptanceStatus);
            equStockin.setFinishTime(finishTime);

            equStockin.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());

            equStockin.setApprovalInfo(approvalInfo);

            //保存stokin
            stockinService.insertEquStockin(equStockin);

            //更新工单状态(流程实例和资产结合的工单)
            String processInstanceId = execution.getProcessInstanceId();
            workOrderAssetRelService.updateWorkOrderStatus(processInstanceId, "已驳回", new Date());
        } catch (ParseException | JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
